import { createApp } from 'vue';
import App from './App.vue';
import { setupRouter } from './router';
import store from './store';

import '@/assets/styles/base/tailwind.css';
import initPlugins from '@/plugins';

import { ConfigProvider } from 'ant-design-vue';
import '@/components/svgIcon';
import SvgIcon from '@/components/svgIcon/svgIcon.vue';

import { changeThemeColor } from '@/utils/theme.js';

import '@vant/touch-emulator';
import { TjPick } from 'tianjian-vue';
import 'tj-design-vue/lib/index.css';
import 'tianjian-vue/es/pick/index.css';

// import 'ant-design-vue/dist/antd.css';
import 'ant-design-vue/dist/antd.variable.min.css';

let history = null;
let router = null;
let app = null;
let isCached = false;
let isMicroMode = window.__MICRO_APP_BROWER_VIEW__;
console.log(isMicroMode, 333);
// 新的对接方式
// console.log('新的对接方法是---方法外面');

if (window.__MICRO_APP_BROWER_VIEW__) {
  // eslint-disable-next-line no-undef
  __webpack_public_path__ = window.__MICRO_APP_PUBLIC_PATH__;
}
function parseRoute(data) {
  // redirectUrl 需要打开的地址
  if (data && data.redirectUrl) {
    const redirectUrl = data.redirectUrl.slice(data.redirectUrl.lastIndexOf('/') + 1);
    console.log(redirectUrl);
    const params = {
      path: '/' + redirectUrl
    };
    // query 查询参数
    if (data.query) {
      params.query = data.query;
    }
    return params;
  }
}

function mount() {
  const { router: _router, history: _history } = setupRouter();
  history = _history;
  router = _router;
  app = createApp(App);
  initPlugins(app);
  app.component('svg-icon', SvgIcon);
  app.use(router);
  app.use(TjPick);
  app.use(store);
  app.mount('#app');
  /** ****自造数据 start**** **/

  if (isMicroMode) {
    // @ts-ignore
    // 监听基座下发的信息
    // ==============================================================================================
    // 新的对接方式
    console.log('方法里面里面里面-新的对接方法是');

    window.provideNotice.addGlobalDataListener(globalData => {
      console.log('订阅通知', globalData);
    });
    // 主动获取
    window.microappSDK.getGlobalData().then(globalData => {
      console.log('主动获取', globalData);
      changeThemeColor(globalData['primary-color']);
      getColor(globalData['primary-color']);
      store.commit('user/setPrimaryColor', globalData['primary-color']);
      sessionStorage.setItem('primaryColor', globalData['primary-color']);
      sessionStorage.setItem('TOKEN', globalData.access_token);
      sessionStorage.setItem('USER_INFO', JSON.stringify(globalData.userInfoData.user));
      sessionStorage.setItem('schoolName', JSON.stringify(globalData.userInfoData.schoolInfo));
      // document.documentElement.style.setProperty('--themecolor', globalData['primary-color']);
    });
    window.provideNotice.addDataListener(data => {
      // if (!data) {
      //   return;
      // }
      console.log('新的全局数据', data);
      let options = data.appNews;
      console.log('appNews 类型数据', options);
      // 'appNews' 为应用消息类型，需要打开指定页面
      if (options.type === 'appNews') {
        const payload = options.payloadAppNews;
        console.log(3232323, payload);
        if (!payload) {
          return;
        }
        const params = parseRoute(payload);
        console.log(params, '99999999999999999999999999999999');
        if (params) {
          setTimeout(() => {
            router.push(params);
          });
        }
      }
      console.log('啊哈哈哈', router.currentRoute.fullPath);
      console.log('heh', options);
      if (isCached && options.path) {
        if (router.currentRoute.fullPath !== '/') {
          router.push(options.path);
        }
      }
    });
    // window.provideNotice.commonNotice(options => {
    //   console.log('公共通信', options);
    // });
    window.microappSDK.getTokenInfo().then(token => {
      console.log('获取token', token.access_token);
      sessionStorage.setItem('TOKEN', token.access_token);
    });
    window.microappSDK.getUserInfo().then(res => {
      console.log('用户信息', res);
      sessionStorage.setItem('USER_INFO', JSON.stringify(res.user));
      sessionStorage.setItem('schoolName', JSON.stringify(res.schoolInfo));
    });
    window.microappSDK.getTheme().then(theme => {
      console.log('主题色', theme);
      // let color = theme['primary-color'];
      // console.log('color', color);
      // console.log('color', color.toString());
      changeThemeColor(theme['primary-color']);
      getColor(theme['primary-color']);
      store.commit('user/setPrimaryColor', theme['primary-color']);
      sessionStorage.setItem('primaryColor', theme['primary-color']);
    });
  } else {
    changeThemeColor('green');
    getColor('green');
    let userInfo = {
      mainOrganizeId: '351303894250303488',
      mainSchoolId: '351303894254497793',
      businessId: '369497383200571392',
      username: '郭亚山',
      idCard: '350502190903075290',
      avatar:
        'https://saas-resource.obs.cn-east-3.myhuaweicloud.com/tenant/2022-11-21/16689970778191659001388569v2-ff6e65d3cfe92a4f3df9e1bc41asdasdasdasdasdasdasdec81dc_720w.jpg'
    };
    store.commit('user/setPrimaryColor', 'green');
    sessionStorage.setItem('USER_INFO', JSON.stringify(userInfo));
    let schoolInfo = {
      isMainSchool: false,
      mainSchoolId: 0,
      schoolId: '346946249116708865',
      organizeId: '346946249091543040',
      schoolName: '自测组织开发专用',
      schoolLogo:
        'https://saas-resource.obs.cn-east-3.myhuaweicloud.com/tenant/2022-8-11/1660211691374v2-ff6e65d3cfe92a4f3df9e1bc41ec81dc_720w.jpg',
      organizeName: '自测组织开发专用'
    };
    sessionStorage.setItem('schoolName', JSON.stringify(schoolInfo));
    sessionStorage.setItem('TOKEN', '38fda554-a9ef-424e-bf27-165bcef7aed8');
    sessionStorage.setItem('primaryColor', 'green');
    /** **** END **** **/
  }
}

function getColor(data, data05) {
  document.documentElement.style.setProperty('--themecolor', data);
  document.documentElement.style.setProperty('--themecolorhover', data05);
  ConfigProvider.config({
    theme: {
      primaryColor: data
    }
  });
}

function unmount() {
  app?.unmount();
  history?.destroy();
  history = null;
  router = null;
  app = null;
  isCached = false;
  localStorage.removeItem('TOKEN');
}

function bootstrap() {
  // @ts-ignore
  window[`micro-app-${window.__MICRO_APP_NAME__}`] = {
    mount,
    unmount
  };
}

if (isMicroMode) {
  bootstrap();
} else {
  mount();
}
